// pages/userConsole/userConsole.js
const db = wx.cloud.database()
Page({

  data: {
    openid: '',
    show: false,
    date: '',
    datalist: [],
    datlist: [],
    expenditure: 0,
    income: 0,
    loading: true,
    datlist_id: 0,
    minDate: new Date().getTime() - 864000000,
    defaultdate: new Date().getTime(),
    maxDate: new Date().getTime(),
    income_id: 0,
    sheetshow: false,
    actions: [
      {
        name: '删除',
      }
    ],
    del_id: ''
  },

  onShow: function (options) {
    this.getdata()

  },
  getdata() {
    let that = this
    console.log('当前用户ID:', wx.getStorageSync('id'));
    that.setData({ openid: wx.getStorageSync('id'), date: '', loading: true, income_id: 0 });
    wx.cloud.callFunction({
      name: 'getlist',
      success: function (res) {
        console.log('云函数返回数据:', res);
        if (!res.result.success) {
          console.error('获取数据失败:', res.result);
          wx.showToast({
            title: '获取数据失败',
            icon: 'none',
            duration: 2000
          })
          that.setData({ loading: false });
          return;
        }
        const result = res.result.data || [];
        // 获取全部数据
        that.setData({
          datalist: result.filter(e => { return e.date.slice(0, 7) == that.formatDatenouth(new Date()) }).sort(function (a, b) {
            return Date.parse(a.date) - Date.parse(b.date);
          }).filter(e => { return e.userid == wx.getStorageSync('id') })
        });
        // 数据整合.
        let ceshi = result.filter(e => { return e.date.slice(0, 7) == that.formatDatenouth(new Date()) }).sort(function (a, b) {
          return Date.parse(a.date) - Date.parse(b.date);
        }).filter(e => { return e.userid == wx.getStorageSync('id') })
        // 收入和支出费用计算
        let expenditure = 0
        let income = 0
        ceshi.filter(e => { return e.money < 0 }).forEach(e => {
          expenditure = expenditure + e.money
        })
        ceshi.filter(e => { return e.money > 0 }).forEach(e => {
          income = income + e.money
        })
        that.setData({ expenditure: expenditure, income: income });
        console.log('支出' + expenditure, '收入' + income)
        // 数据根据日期分类
        let ceshidata = []
        ceshi.forEach(e => {
          ceshidata.push(e.date)
        })
        let datlist = []
        for (var i = 0; i < Array.from(new Set(ceshidata)).length; i++) {
          let ceshidatas = ceshi.filter(e => { return e.date == Array.from(new Set(ceshidata))[i] })
          let expenditure = 0;
          let income = 0;
          ceshidatas.filter(e => { return e.money < 0 }).forEach(e => {
            expenditure = expenditure + e.money
          })
          ceshidatas.filter(e => { return e.money > 0 }).forEach(e => {
            income = income + e.money
          })
          datlist.push({ date: Array.from(new Set(ceshidata))[i], data: ceshi.filter(e => { return e.date == Array.from(new Set(ceshidata))[i] }), expenditure: expenditure, income: income })
          // 单日收入和支出计算
        }
        that.setData({ datlist: datlist, loading: false, datlist_id: 1, income_id: 1 });
      },
      fail: function(error) {
        console.error('调用云函数失败：', error)
        wx.showToast({
          title: '获取数据失败',
          icon: 'none',
          duration: 2000
        })
        that.setData({ loading: false });
      }
    })
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  formatDate(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    const d = (dt.getDate() + "").padStart(2, "0");
    return `${y}-${m}-${d}`;
  },
  formatDatenouth(date) {
    const dt = new Date(date);
    const y = dt.getFullYear();
    const m = (dt.getMonth() + 1 + "").padStart(2, "0");
    return `${y}-${m}`;
  },
  onConfirm(event) {
    this.setData({
      show: false,
      date: this.formatDate(event.detail),
      loading: true,
      datlist_id: 0,
      income_id: 0
    });
    let that = this
    wx.cloud.callFunction({
      name: 'getlist',
      success: function (res) {
        // 获取全部数据
        console.log(res.result.filter(e => { return e.date == that.data.date }))
        that.setData({ datalist: res.result.filter(e => { return e.date == that.data.date }).filter(e => { return e.userid == wx.getStorageSync('id') }) });
        // 数据整合.
        let ceshi = res.result.filter(e => { return e.date == that.data.date }).filter(e => { return e.userid == wx.getStorageSync('id') })
        // 收入和支出费用计算
        let expenditure = 0
        let income = 0
        ceshi.filter(e => { return e.money < 0 }).forEach(e => {
          expenditure = expenditure + e.money
        })
        ceshi.filter(e => { return e.money > 0 }).forEach(e => {
          income = income + e.money
        })
        that.setData({ expenditure: expenditure, income: income });
        console.log('支出' + expenditure, '收入' + income)
        // 数据根据日期分类
        let ceshidata = []
        ceshi.forEach(e => {
          ceshidata.push(e.date)
        })
        let datlist = []
        for (var i = 0; i < Array.from(new Set(ceshidata)).length; i++) {
          let ceshidatas = ceshi.filter(e => { return e.date == Array.from(new Set(ceshidata))[i] })
          let expenditure = 0;
          let income = 0;
          ceshidatas.filter(e => { return e.money < 0 }).forEach(e => {
            expenditure = expenditure + e.money
          })
          ceshidatas.filter(e => { return e.money > 0 }).forEach(e => {
            income = income + e.money
          })
          datlist.push({ date: Array.from(new Set(ceshidata))[i], data: ceshi.filter(e => { return e.date == Array.from(new Set(ceshidata))[i] }), expenditure: expenditure, income: income })
          // 单日收入和支出计算
        }
        that.setData({ datlist: datlist, loading: false, datlist_id: 1, income_id: 1 });
      }, fail: console.error
    })
  },
  deldata(event) {
    console.log(event)
    this.setData({ sheetshow: true, del_id: event.target.dataset.item._id });
  },
  onClose() {
    this.setData({ sheetshow: false });
  },
  onSelect(event) {
    let that = this
    console.log(event.detail);
    // 删除逻辑
    db.collection('record').doc(this.data.del_id).remove({
      success: res => {
        wx.showToast({
          title: '删除成功',
        })
        that.getdata()
      }, fail: err => {
        wx.showToast({
          icon: 'none',
          title: '删除失败',
        })
      }
    })
  },
})